package com.hhz.mp;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.additional.query.impl.LambdaQueryChainWrapper;
import com.hhz.mp.mapper.UserMapper;
import com.hhz.mp.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

/**
 * mp lambda 条件构造器
 *
 * @Author Rem
 * @Date 2020-03-01
 */

@Slf4j
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class MyApplicationTest3_2 {

    @Autowired
    private UserMapper userMapper;


    /**
     * lambda根据条件查询
     * SELECT id, user_name, name, age, email AS mail, version, deleted, sex FROM tb_user WHERE deleted = 0 AND name LIKE ? AND age < ?
     */
    @Test
    public void selectLambda() {
        //创建对象的三种方式
        LambdaQueryWrapper<User> lambda = new QueryWrapper<User>().lambda();

        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        LambdaQueryWrapper<User> lambdaQuery = Wrappers.lambdaQuery();

        //SELECT id, user_name, name, age, email AS mail, version, deleted, sex FROM tb_user WHERE deleted = 0 AND name LIKE ? AND age < ?
        lambdaQuery.like(User::getName, "李").lt(User::getAge, 40);

        List<User> users = userMapper.selectList(lambdaQuery);
        users.forEach(System.err::println);
    }

    /**
     * lambda根据条件查询
     * 查询姓名为孙姓 并且 （年龄小于40或者邮箱不为空）
     * SELECT id, user_name, name, age, email AS mail, version, deleted, sex FROM tb_user WHERE deleted = 0 AND name LIKE ? AND (age < ? OR email IS NOT NULL)
     */
    @Test
    public void selectLambda2() {
        LambdaQueryWrapper<User> wrapper = new QueryWrapper<User>().lambda();
        wrapper.likeRight(User::getName, "孙")
                .and(e -> e.lt(User::getAge, 40).or().isNotNull(User::getMail));
        List<User> users = userMapper.selectList(wrapper);
        users.forEach(System.err::println);
    }

    /**
     * 3.0.7后的新的wrapper 可以直接返回结果
     * LambdaQueryChainWrapper
     */
    @Test
    public void selectLambda3() {

        List<User> list = new LambdaQueryChainWrapper<>(userMapper)
                .like(User::getName, "孙").list();

        list.forEach(System.err::println);
    }

}